<?php


namespace app\api\controller\v1;


use app\api\controller\v1\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use Predis\Command\Redis\DUMP;
use think\Db;

/**
 * 河北佰银
 */
class HeBeiBaiYIn
{
    private $platformId;
    private $tenantId;
    private $key;

    public function __construct() {

//            $this->platformId = '1640276235542462464';
//            $this->tenantId = '1643873158463614977';
//            $this->key = '5945046671425740';

        $this->platformId = '1807247594532241408';
        $this->tenantId = '1789139655184089088';
        $this->key = '7923718291637249';

    }

    public function pushClue($mapping,$clue_info,$listPush)
    {

        $apiName='【'.$mapping['api_name'].'】';

//        $clue_info['clue_name']='测试';
//        $clue_info['phone']='13000000001';

        $this->getValidate($apiName,$clue_info); // 手机号码的撞库
        $clue_rule = json_decode($mapping['rule_json'], true);
        $params = [];
        if(!$clue_rule){
            $errMsg=$apiName.'读取商户接收规则失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }else{

            foreach ($clue_rule as $v){
                $params[$v['curr']] = $clue_info[$v['orig']];
                if($v['orig'] == 'city'){
                    $citys = explode('-',$clue_info[$v['orig']]);
                    $city_info = Db::name('city')->where(['type'=>2,'id'=>$citys[1]])->find();
                    $params[$v['curr']] = $city_info['name'];
                }
            }

            if($clue_info['gender']==1){
                $params['sex']='男';
            }elseif ($clue_info['gender']==2){
                $params['sex']='女';
            }

//            $params['name']='测试长';
//            $params['phone']='15922583788';
//            $params['t3']=1;
//            if(strpos($clue_info['apply_limit'], '万') !== false){
//                $params['customerAmount']=$clue_info['apply_limit'];
//            }else{
//                $params['customerAmount']=$clue_info['apply_limit'].'元';
//            }

            if(strpos($clue_info['apply_limit'], '-') !== false){
                $moneyArr=explode('-',$clue_info['apply_limit']);
                $moneyNum=count($moneyArr);
                if($moneyNum==1){
                    $MoneyStr=$moneyArr[0];
                }else{
                    $MoneyStr=$moneyArr[1];
                }
            }else{
                $MoneyStr=$clue_info['apply_limit'];
            }
            if(strpos($MoneyStr, '万') !== false){
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['customerAmount']=intval($MoneyStr).'万元';
            }else{
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['customerAmount']=intval($MoneyStr).'元';
            }

            if (!empty($clue_info['show_city'])) {
                if (strpos($clue_info['show_city'], '-') !== false) {
                    $city_t = explode('-', $clue_info['show_city']);
                    $city_info = clue_city_transform($city_t);
                }else{
                    $params['city']=$clue_info['show_city'];
                    $city_info=Db::name('city')->where(['type' => 2, 'name' => $clue_info['show_city']])->find();
                }
                if(empty($city_info)){
                    $errMsg=$apiName.'显示城市匹配失败';
                    ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
                    model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                    throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
                }else{
                    $params['cityCode']=$city_info['code'];
                    $params['provinceCode']=Db::name('city')->where(['id'=>$city_info['pid']])->value('code');
                }
            }else{
                if(!empty($clue_info['city'])){
                    $citys = explode('-',$clue_info['city']);
                    $city_info1 = Db::name('city')->where(['id'=>$citys[0]])->find();
                    $city_info2 = Db::name('city')->where(['id'=>$citys[1]])->find();

                    $params['provinceCode']=$city_info1['code'];//省code
                    $params['cityCode']=$city_info2['code'];//市code
                }
            }


            if($clue_info['pro_id']==3){
                $params['houseNum']=1;
            }elseif ($clue_info['pro_id']==4){
                $params['vehicleNum']=2;
            }elseif ($clue_info['pro_id']==6){
                $params['accumulationFundNum']=1;
            }else{
                $errMsg=$apiName.'线索推送商户处理失败贷款类型不符';
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$params);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }


//            $advInfo=Db::name('account')->where('adv_id',$clue_info['adv_id'])->find();

//            if(!empty($clue_info['push_channel'])){
//                $remarkStr=$clue_info['push_channel'].'-';
//            }else{
//                if($clue_info['type']==1){
//                    $remarkStr='百度-';
//                }elseif ($clue_info['type']==2){
//                    $remarkStr='腾讯-';
//                }elseif ($clue_info['type']==3){
//                    $remarkStr='抖音-';
//                }else{
//                    $remarkStr=$advInfo['show_channel'].'-';
//                }
//            }

            //渠道

            if(!empty($clue_info['push_channel'])){
                $source=$clue_info['push_channel'];
            }else{
                $advInfo=Db::name('account')->where('adv_id',$clue_info['adv_id'])->find();
                $source=$advInfo['show_channel'];
                if(empty($source)){
                    $source=get_channel_desc($clue_info['type']);

                }
            }
            $remarkStr=$source.'-';


//            $params['extendTwo']=$advInfo['acc_desc'];

            if(empty($clue_info['remark'])){
            }else{
                $remark=json_decode($clue_info['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if(strpos($kk, '城市') !== false){
                            }else{
                                $remarkArr[]=$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($clue_info['type']==1){
                                if(strpos($vv['name'], '城市') !== false){
                                }else{
                                    $remarkArr[]=$vv['value'];
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    if(strpos($vv['name'], '城市') !== false){
                                    }else{
                                        $remarkArr[]=$vv['value'];
                                    }
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr[]=$remark;
                }
                $remarkStr=$remarkStr.implode('|',$remarkArr);
            }

            $params['extendOne']=$remarkStr;
            $params['customerCreateTime']=date('Y-m-d');

//            dump('参数');
//            dump(json_encode($params,JSON_UNESCAPED_UNICODE));
//            die;

            $str = openssl_encrypt(json_encode($params,JSON_UNESCAPED_UNICODE), 'AES-128-ECB' , $this->key,OPENSSL_RAW_DATA);
            $data = base64_encode($str);

            $api_url = $mapping['api_url'];

            $postApi=[
                'data'=>$data,
                'platformId'=>$this->platformId,
                'tenantId'=>$this->tenantId
            ];


            $str='';
            foreach ($postApi as $key => $value) {

                $str .= $key.'='.$value.'&';

            }
//            \dump('签名串');
//            \dump($str.'key='.$this->key);
            $sign=md5($str.'key='.$this->key);
            $postApi['sign']=$sign;


            $postData['data']=$postApi;
            $postData['param']=$params;

//            \dump($postData);
//            die;

//            \dump('提交');
//            \dump($api_url);
//            \dump($postApi);
            // 2. 推送线索
            $res_json = $this->postJson($api_url, $postApi);
//            \dump($res_json);
            $res  = json_decode($res_json, true);
//            dump($res);
//            die;
            if(!empty($res)){
                $res['params'] = $postData;
                if($res['code']!=200){
                    $errMsg=$apiName.'线索推送商户处理失败';
                    ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                    model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['msg']]);
                    throw new ParamException(['msg'=>$errMsg.$res['msg'],'errorCode'=>10001]);
                }else{
                    //看DATA0 是否有数据成功
//                    if(!empty($res['data'][0])){
//                        if(strpos($res['data'][0], '数据成功') === false) {
//                            $errMsg=$apiName.'线索推送商户处理失败';
//                            ClueErrorLog::record($clue_info['clue_id'],'线索推送商户处理失败',$res);
//                            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['data'][0]]);
//                            throw new ParamException(['msg'=>$errMsg.$res['data'][0],'errorCode'=>10001]);
//                        }
//                    }else{
//                        $errMsg=$apiName.'线索推送商户处理失败';
//                        ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                        model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['msg']]);
//                        throw new ParamException(['msg'=>$errMsg.$res['msg'],'errorCode'=>10001]);
//                    }
                }
            }else{
                $errMsg=$apiName.'线索推送商户请求失败';
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$postData);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }

            return $res;
        }
    }


    //可以直接用
    public function getValidate($apiName,$clue_info)
    {
        $phone=$clue_info['phone'];
//        $api_url = 'http://cdsxyc.v6.idcfengye.com/dev-api-dy/customer/verification/repeatPhone';
        $api_url = 'https://xl.cdsxyc.com/api-xl/customer/verification/repeatPhone';

        $api_params = [
            'tenantId'=>$this->tenantId,
            'type'=>1,
            'phone'=>$phone

        ];
        $res_json = $this->postJson($api_url, $api_params);
        $res  = json_decode($res_json, true);

//        \dump($res);
//        die;

        if(!empty($res)){
            //手机重复
            if($res['code']==902){

                $errMsg=$apiName.'CRM手机号码的撞库重复：'.$res['msg'];
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);

//                if(empty($clue_info['is_find'])&&!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city']){
//                    $clue_info['city'] = $clue_info['clue_city'];
//                    $clue_info['next_city'] = $clue_info['clue_city'];
//                    $listPush[]=$clue_info['push_id'];
//                    $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                    if($clueRes['code']!=200){
//                        $errMsg=$clueRes['msg'];
//                        ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                        model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                        throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                    }
//                }else{
//                    $errMsg=$apiName.'CRM手机号码的撞库重复';
//                    ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                    model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                    $isRe=Db::name('clue_err_log')->where(['type'=>2,'adv_id'=>$clue_info['adv_id'],'pro_id'=>$clue_info['pro_id'],'clue_id'=>$clue_info['id']])->find();
//                    if(empty($isRe)){
//                        Db::name('clue_err_log')->insert([
//                            'type'=>2,
//                            'clue_id'=>$clue_info['id'],
//                            'adv_id'=>$clue_info['adv_id'],
//                            'pro_id'=>$clue_info['pro_id'],
//                            'city'=>$clue_info['city'],
//                            'create_time'=>time()]);
//                    }
//                    if(empty($clue_info['is_find'])){
//                        $listPush[]=$clue_info['push_id'];
//                        $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                        if($clueRes['code']!=200){
//                            $errMsg=$clueRes['msg'];
//                            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }else{
//                        throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                    }
//                }
            }else{
                if($res['code']!=200){
                    $errMsg=$apiName.'CRM手机号码的撞库失败：'.$res['msg'];
                    ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                    model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                    throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
                }
            }
        }else{
            $errMsg=$apiName.'CRM手机号码的撞库请求失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }
        return $res;
    }

    public function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }

    /**
     * post发送json格式的数据
     */
    public function postJson($url, $data)
    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            throw new ParamException(['msg'=>'请求数据不能为空','errorCode'=>10000]);
        }
        $data=json_encode($data,JSON_UNESCAPED_UNICODE);
//        \dump($data);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
//            'token:3dcb0d2dba347b40476bc3294c60fdfe' ,

        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

}